var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var SqlHelper = utils.SqlHelper;
var jwt = require('../../utils/jwt.js')
var dateHelper = require('../../utils/date.js')

var WebSocketServer = require('websocket').server;

var randRommId = 0;
var map = new Map();

// 创建房间
const createRoom = function (user1) {

    randRommId++;
    var roomInfo = { user1: user1, user2: null, scene1: true, scene2: true }; // true表示可以播放,false表示不能播放
    map.set(randRommId, roomInfo);
    user1.roomId = randRommId;
    user1.isMaster = true; // 主机

    user1.sendUTF("createDown|" + randRommId);  // 告诉主句，已经有人加入

}

// 加入房间 (返回房间号)
const joinRoom = function (roomId, user2) {

    var roomInfo = map.get(parseInt(roomId));

    if (!roomInfo || roomInfo.user2) {
        user2.sendUTF("joinFail");
    } else {
        roomInfo.user2 = user2;
        user2.roomId = roomId;
        user2.isMaster = false;
        roomInfo.user1.sendUTF("joinDown|" + roomId);  // 告诉主机，已经有人加入
    }

}

// 场景播放结束
const playOver = function (connection) {

    var roomInfo = map.get(parseInt(connection.roomId));

    if (connection.isMaster && roomInfo.scene1 == false) {
        // console.log('场景1播放完了，准备播放下一个了')
        roomInfo.scene1 = true;
        roomInfo.user2.sendUTF("firendIsReady");  // 告诉朋友，已经准备好了
    } else if (roomInfo.scene2 == false) {
        // console.log('场景2播放完了，准备播放下一个了')
        roomInfo.scene2 = true;
        roomInfo.user1.sendUTF("firendIsReady");  // 告诉朋友，已经准备好了
    }

}

//  请求播放场景
const requestPlay = function (connection) {
    var roomInfo = null;
    if (connection.roomId) {
        roomInfo = map.get(parseInt(connection.roomId));
    }

    if (!roomInfo) {
        connection.sendUTF('noroom');
        return;
    }

    // 是否都结束，都结束了就发送播放下一个命令
    if (roomInfo.scene1 && roomInfo.scene2 && roomInfo.scene1 == true && roomInfo.scene2 == true && roomInfo.user1 && roomInfo.user2) {
        // sendCmd(roomId, "playVideo");
        roomInfo.scene1 = false;
        roomInfo.scene2 = false;
        roomInfo.user1.sendUTF('playVideo');
        roomInfo.user2.sendUTF('playVideo');;
    } else {
        connection.sendUTF('playfail');
    }
}

// 同时发给两个人的命令封装
const sendCmd = function (roomId, cmd, params) {
    var roomInfo = map.get(parseInt(roomId));
    roomInfo.user1.sendUTF(cmd + '|' + params);
    roomInfo.user2.sendUTF(cmd + '|' + params);
}

const receiveCmd = function (connection, message) {
    var cmd = message.split("|")[0];
    var params = message.split("|")[1];
    var params2 = message.split("|")[2];

    if (cmd == "createRoom") {
        createRoom(connection); // 返回房间号，然后生成二维码
    } else if (cmd == "joinRoom") {
        joinRoom(params, connection);
    } else if (cmd == "playOver") {
        playOver(connection);      // 手机某个画面播放完毕
    } else if (cmd == "requestPlay") {
        requestPlay(connection);
    }

}

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false,
    keepaliveInterval: 5000
});

function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    console.log(origin);
    return true;
}

wsServer.on('request', function (request) {
    // console.log('接受到websocket请求 1' )

    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }

    // console.log('接受到websocket请求 2')

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');

    connection.on('message', function (message) {

        receiveCmd(connection, message.utf8Data);




        // if (message.type === 'utf8') {
        //     console.log('Received Message: ' + message.utf8Data);
        //     connection.sendUTF(message.utf8Data);
        // }
        // else if (message.type === 'binary') {
        //     console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        //     connection.sendBytes(message.binaryData);
        // }
    });
    connection.on('close', function (reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
        if (connection.roomId) {
            var roomInfo = map.get(parseInt(connection.roomId));
            if (roomInfo && roomInfo.user1) {
                roomInfo.user1.close();
            }
            if (roomInfo && roomInfo.user2) {
                roomInfo.user2.close();
            }
            map.delete(connection.roomId);
        }

        // 目前还有的房间数量
        console.log("目前还有：" + map.size + "房间")

    });
});



var connect = function (req, res) {

    // 随机一个唯一的id值，给对方
    var randId = Math.round(Math.random() * 1000) + Date.now();

}


var analysisFn = function (req, res, next) {
    var body = req.body || req.query;

    var cmd = body.cmd;

    // 命令解析
    if (!cmd) {
        return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }

    switch (cmd) {
        case 'connect':
            connect(req, res);  // 登记
            break;
        default:
            return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)